########################################
#### figure_2.R: Generates Figure 2 ####
########################################

dta_accuracy$endtime <- as.Date(dta_accuracy$endtime)
dta_accuracy$accuracyre5 <- 6-dta_accuracy$accuracy
dta_accuracy$pre <- "pre"
dta_accuracy$pre[dta_accuracy$endtime > "2022-11-08"] <- "post"
fig_ot_a = dta_accuracy %>% ggplot(aes(y = accuracyre5, x=endtime, color=pid, fill=pid, group=interaction(pre,pid))) +
  geom_smooth(method = "loess") +
  scale_fill_manual(values=c("Democrat" ="#013369", "Republican" = "#D50A0A")) +
  scale_color_manual(values=c("Democrat" ="#013369", "Republican" = "#D50A0A")) + 
  guides(fill=guide_legend(title="Respondent Partisanship"), color="none") + 
  theme_prl()+ 
  scale_y_continuous(breaks = seq(1,5,1), 
                     labels = c("Strongly disagree", "Disagree", 
                                "Neither agree\nnor disagree", 
                                "Agree", "Strongly agree"), 
                     limits= c(1, 5)) +
  geom_hline(yintercept=3, linetype="dotted", color="black") +
  geom_vline(xintercept=as.numeric(dta_accuracy$starttime[854]), linetype="solid") +
  facet_grid(.~pid) +
  theme(axis.text.x = element_text(angle = 45, hjust=1))+
  theme( # remove the vertical grid lines
    panel.grid.major.x = element_blank(),
    #plot.subtitle = element_text(hjust = 0, size = rel(.5)),
    axis.title.y=element_blank(),
    axis.title.x=element_blank(),
    legend.position = "none") +
  labs(subtitle = "Short/Medium-Term Change",
       caption = "N = 5,244")

#### Over-Time with Full Data ####
fig_ot_b = dta_overtime |> 
  mutate(accuracy_rev = 6 - accuracy) |> 
  ggplot(aes(x = date, y = accuracy_rev, color = pid, fill = pid, weight = weight)) +
  geom_smooth(show.legend = F, method = 'loess') +
  facet_wrap(~ pid, ncol = 3) +
  scale_color_manual(values = c("dodgerblue3", "grey50", "firebrick3")) +
  scale_fill_manual(values = c("dodgerblue3", "grey50", "firebrick3")) +
  scale_y_continuous(breaks = 1:5, labels = c("Strongly disagree", "Disagree",
                                              "Neither agree\nnor disagree",
                                              "Agree", "Strongly agree"),
                     limits = c(1,5)) +
  geom_hline(yintercept = 3, lty = "dotted") + 
  labs(x = NULL, y = NULL,
       subtitle = "Long-Term Change",
       caption = "N = 60,182") +
  theme_prl() +
  theme(axis.text.x = element_text(angle = 45, hjust = 1))

fig2 = plot_grid(fig_ot_a, fig_ot_b, labels  = c("A", "B"))


ggsave(here("Figures", "figure_2.pdf"), fig2,
       dpi = 600, units = "in", height = 6, width = 14)
